//
//  ReportDetailVC.m
//  efairy
//
//  Created by 李锋 on 2019/3/13.
//  Copyright © 2019年 East. All rights reserved.
//

#import "ReportDetailVC.h"
#import <MJRefresh.h>
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "ReportBasicModel.h"
#import "ReportBasicInfoCell.h"
#import "ReportDeviceAlarmModel.h"
#import "ReportDeviceAlarmCell.h"
#import "ReportProjectDetailVC.h"
#import "ReportVC.h"


@interface ReportDetailVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) MJRefreshComponent * refreshViewComponent;
@property (nonatomic, strong) ReportBasicModel *basicModel;
@property (nonatomic, strong) NSMutableArray<ReportDeviceModel *> *deviceAlarmList;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, assign) int order;//根据分数排序，0-升序，1-降序
@property (nonatomic, strong) NSString *keyword;//查询关键字
@property (nonatomic,strong)UIView *cellSearchView;
@property (nonatomic,strong)UIView *mSearchView;
@property (nonatomic,strong)UITextField *mTextField;
@property(nonatomic, strong)UILabel *mScore;//评分统计
@property(nonatomic,strong)UIImageView *mUpImageView;//评分按升序查询
@property(nonatomic,strong)UIImageView *mDownImageView;//评分按降序查询
@property(nonatomic,assign)BOOL isoclickUpOrder;
@end

@implementation ReportDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageIndex = 1;
    _order = 0;
    _keyword = @"";
//    _deviceAlarmList = [[NSMutableArray alloc]init];
    [self setNavigationBar];
    [self initView];
    [self queryBasicInfo];
}

-(void)setNavigationBar{
    self.navigationItem.title = @"报告详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"global_nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backReportVC)];
    
}


- (void)backReportVC {
    // 返回到任意界面
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[ReportVC class]]) {
            [self.navigationController popToViewController:temp animated:YES];
        }
    }
}



-(void)initView{
    self.view.backgroundColor = ColorFromRGB(0xeff0f4);
    float barHeight = self.navigationController.navigationBar.frame.size.height;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, statusBarHeight+barHeight, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-barHeight)];
    _tableView.backgroundColor = ColorFromRGB(0xeff0f4);
    _tableView.delegate = self;//设置代理
    _tableView.dataSource = self;//设置代理
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分割线为隐藏
    __weak  typeof(self) weakSelf = self;
    
    //下拉刷新
//    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
//        weakSelf.pageIndex = 1;
//        [weakSelf queryReportProjectInfo:YES];
//    }];
    
    //上啦刷新
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
            weakSelf.pageIndex = weakSelf.pageIndex + 1;
            [weakSelf queryReportProjectInfo:NO];
    }];
    
    
    _mSearchView = [[UIView alloc]initWithFrame:CGRectMake(0, statusBarHeight+barHeight, SCREEN_WIDTH, 40)];
    _mSearchView. backgroundColor = ColorFromRGB(0xffffff);
    _mSearchView.hidden = YES;
    
    //搜索栏背景
    UIView *searchBg =  [[UIView alloc]init];
    searchBg.layer.borderWidth=0.0f;
    searchBg.layer.cornerRadius=16.0f;
    searchBg.backgroundColor = ColorFromRGB(0xefefef);
    [_mSearchView addSubview:searchBg];
    
    //创建左侧搜索图标
    UIImageView *searchIcon=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 15, 15)];
    searchIcon.image=[UIImage imageNamed:@"search_icon"];
    [_mSearchView addSubview:searchIcon];
    
    //文本输入框
    _mTextField = [[UITextField alloc]init];
    _mTextField.backgroundColor = ColorFromRGB(0xefefef);
    _mTextField.clearButtonMode=UITextFieldViewModeAlways;//只要输入框有内容就出现
    // 设置提示文字
    _mTextField.placeholder = @"请输项目名称";
    _mTextField.layer.borderWidth=0.0f;
    _mTextField.layer.cornerRadius=16.0f;
    _mTextField.returnKeyType = UIReturnKeySearch;//变为搜索按钮
    _mTextField.delegate = self;//设置代理
    [_mSearchView addSubview:_mTextField];
    
    UILabel *scoreLabel = [[UILabel alloc]init];
    scoreLabel.text = @"评分";
    scoreLabel.textColor = ColorFromRGB(0x333333);
    scoreLabel.font = [UIFont systemFontOfSize:14.f];
    [_mSearchView addSubview:scoreLabel];
    
    _mUpImageView = [[UIImageView alloc]init];
    _mUpImageView.userInteractionEnabled  = YES;//可被点击
    _mUpImageView.image = [UIImage imageNamed:@"icon_score_ascending"];
    _mUpImageView.tag = 0;
    UITapGestureRecognizer *upOrder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickOrder:)];
    [_mUpImageView addGestureRecognizer:upOrder];
    [_mSearchView addSubview:_mUpImageView];
    
    _mDownImageView = [[UIImageView alloc]init];
    _mDownImageView.userInteractionEnabled  = YES;//可被点击
    _mDownImageView.image = [UIImage imageNamed:@"icon_score_down_no"];
    _mDownImageView.tag = 1;
      UITapGestureRecognizer *downOrder= [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickDownOrder:)];
    [_mDownImageView addGestureRecognizer:downOrder];
    [_mSearchView addSubview:_mDownImageView];
    
    searchBg.sd_layout.heightIs(30)
    .topSpaceToView(_mSearchView, 5)
    .leftSpaceToView(_mSearchView, 16)
    .rightSpaceToView(_mSearchView, 75);
    
    searchIcon.sd_layout.heightIs(15)
    .widthIs(15)
    .topSpaceToView(_mSearchView, 12.5)
    .leftSpaceToView(_mSearchView, 32);
    
    _mTextField.sd_layout.heightIs(30)
    .topSpaceToView(_mSearchView, 5)
    .leftSpaceToView(searchIcon, 12)
    .rightSpaceToView(_mSearchView, 75);
    
    scoreLabel.sd_layout.widthIs(29).heightIs(14).rightSpaceToView(_mSearchView, 30).topSpaceToView(_mSearchView, 13);
    _mUpImageView.sd_layout.widthIs(8).heightIs(4).topSpaceToView(_mSearchView, 14).rightSpaceToView(_mSearchView, 16);
    _mDownImageView.sd_layout.widthIs(8).heightIs(4).topSpaceToView(_mUpImageView, 4).rightSpaceToView(_mSearchView, 16);
    
    
    
    [self.view sd_addSubviews:@[_tableView,_mSearchView]];
}


-(void)backRootVC{
    self.navigationController.tabBarController.hidesBottomBarWhenPushed=NO;
    self.navigationController.tabBarController.selectedIndex=0;
    [self.navigationController popToRootViewControllerAnimated:YES];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(_cellSearchView){
        if(scrollView.contentOffset.y > _cellSearchView.frame.origin.y+1){
            if(_mSearchView.hidden){
                _mSearchView.hidden = NO;
            }
        }else if(scrollView.contentOffset.y < _cellSearchView.frame.origin.y){
            if(!_mSearchView.hidden){
                _mSearchView.hidden = YES;
            }
        }
    }

}

 //0升序
-(void)onClickOrder:(id)tap{
    [_deviceAlarmList removeAllObjects];
    _order = 0;
    _mUpImageView.image = [UIImage imageNamed:@"icon_score_ascending"];
    _mDownImageView.image = [UIImage imageNamed:@"icon_score_down_no"];
    [self.tableView reloadData];
    //tableview 刷新完毕
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self queryReportProjectInfo:YES];
    });
}

//1降序
-(void)onClickDownOrder:(id)tap{
    [_deviceAlarmList removeAllObjects];
    _order = 1;
    _mUpImageView.image = [UIImage imageNamed:@"icon_score_ascending_no"];
    _mDownImageView.image = [UIImage imageNamed:@"icon_score_down"];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self queryReportProjectInfo:YES];
    });
}


#pragma mark -UITextFieldDelegate
//搜索 这个函数是重写UITextFieldDelegate 当点击键盘搜索按钮触发
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    _keyword = self.mTextField.text;
    [_deviceAlarmList removeAllObjects];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self queryReportProjectInfo:YES];
    });
    return YES;
}


//颜值搜索栏输入的长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
    if (range.length == 1 && string.length == 0) {
       return YES;
    }else if (textField.text.length >= 30) {
        self.mTextField.text = [textField.text substringToIndex:30];
        return NO;
    }
    return YES;
}


#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_deviceAlarmList && _deviceAlarmList.count > 0){
        return _deviceAlarmList.count +1;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if(section == 0){
//        return 1;
//    }else if(section == 1){
//        if(_deviceAlarmList && _deviceAlarmList.count > 0){
//            return _deviceAlarmList.count;
//        }
//    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        ReportBasicInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportBasicInfoCell" description]];
        if(!cell){
            cell = [[ReportBasicInfoCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;//点击无任何样式变化
            _cellSearchView = cell.searchView;
            cell.scoreQeuryBlock = ^(int type) {
                _order = type;
                _pageIndex = 1;
                [self queryReportProjectInfo:YES];
            };
            cell.queryByKeywordBlock = ^(NSString * _Nonnull keyword) {
                _keyword = keyword;
                self.mTextField.text = keyword;
                [self queryReportProjectInfo:YES];
            };
            
            cell.shouldChangeBlock = ^(NSString * _Nonnull keyword) {
                _keyword = keyword;
            };
            
            cell.saveReportTitleBlock = ^(NSString * _Nonnull reportTitle) {
                [self saveReportTitle:reportTitle];
            };
        }
        if(_basicModel){
             [cell setDataModel:_basicModel keyword:_keyword order:_order];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else{
        ReportDeviceAlarmCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportDeviceAlarmCell" description]];
        if(!cell){
            cell = [[ReportDeviceAlarmCell alloc]init];
            cell.layer.cornerRadius = 6;
            cell.layer.masksToBounds = YES;
            cell.callPhoneBlock = ^(NSInteger index) {
                [self callSomeOneWithPhoneNum:_deviceAlarmList[index].efairyproject_user_phonenumber];
            };
        }
//        [cell layoutIfNeeded];
//        cell.tableViewHeight =_deviceAlarmList[indexPath.section-1].efairyproject_device_statistics.device_statistics_list.count * 34+10;
        if(_deviceAlarmList){
              [cell setDataModel:_deviceAlarmList[indexPath.section-1] arrayIndex:indexPath.section-1];
        }
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
        
    }
  
}

#pragma UITableViewDelegate

////cell自适应高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return  [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
    }else{
//        height = [tableView cellHeightForIndexPath:indexPath model:_deviceAlarmList[indexPath.section-1] keyPath:@"tableView" cellClass:[ReportDeviceAlarmCell class] contentViewWidth:SCREEN_WIDTH];
        
       return _deviceAlarmList[indexPath.section-1].efairyproject_device_statistics.device_statistics_list.count *44+89+34+8 ;
    }
   
    
    
}

//section header高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section > 0){
        return 8.f;
    }else{
        return 0.0001;
    }
    
}

//section footer高度设置
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

//设置section中header的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//设置sectin中footer的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section > 0){
        ReportProjectDetailVC *vc = [[ReportProjectDetailVC alloc]init];
        vc.reportId = self.reportId;
        vc.projectId =  _deviceAlarmList[indexPath.section-1].efairyproject_id;
        [self showViewController:vc sender:nil];
    }
}


-(void)queryBasicInfo{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
  
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId
                              };
    
    NSLog(@"报表项目列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager apiReportBasicInfo] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取可生成报表的项目列表%@",responseObject);
        [hud hideAnimated:YES];
         _basicModel=  [ReportBasicModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self queryReportProjectInfo:YES ];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}




//停止刷新头部或者底部
- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}


//查询根据项目已生成的报表列表（每个设备的报警信息）
-(void)queryReportProjectInfo:(BOOL)isHeader{
    
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    if(isHeader){
        _pageIndex = 1;
    }
    
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId,
                              @"keyword":_keyword,
                              @"order":@(_order),
                              @"page":@(_pageIndex),
                              @"size":@"5",
                              };
    
    NSLog(@"设备报表列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager apiReportProjectInfoList] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取的设备报表列表%@",responseObject);
        [hud hideAnimated:YES];
        [self tableViewEndRefresh:isHeader];
        ReportDeviceAlarmModel *model=  [ReportDeviceAlarmModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        if(model.efairyreport_project_list != nil){
            if(isHeader){
                _deviceAlarmList = model.efairyreport_project_list;
            }else{
                //上啦加载追加数据到数组
                [_deviceAlarmList addObjectsFromArray:model.efairyreport_project_list];
            }
            if(_deviceAlarmList.count >= model.total_rows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }
        }
        //刷新数据
        [self.tableView reloadData];
        
       
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


-(void)saveReportTitle:(NSString *)title{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    if(title == nil || [title isEqualToString:@""]){
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入标题"];
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    
    [params setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [params setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [params setObject:_reportId == nil ?@"":_reportId forKey:@"efairyreport_id"];
    [params setObject:title forKey:@"efairyreport_title"];
    
    
    NSLog(@"报表项目列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    [[XDAFNetworking sharedInstance]PUT:[ApiManager apiReport] parameters:params  success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取可生成报表的项目列表%@",responseObject);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"保存成功"];
        [hud hideAnimated:YES];
      
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}



//根基手机号自动跳到打电话页面
- (void)callSomeOneWithPhoneNum:(NSString*)phoneNum {
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",phoneNum];
    NSLog(@"电话%@",callPhone);
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}
@end
